﻿using System;
using System.Diagnostics;
using mki.Backup.Helper;
using System.IO;
using System.Threading;
using mki.Backup.Objects;

namespace mki.Backup.Interfaces
{
	/// <summary>
	/// Run process Job
	/// </summary>
	internal class RunProcessJob
	{
		#region Methods (1)

		// Public Methods (1) 

		/// <summary>
		/// Runs the job.
		/// </summary>
		/// <param name="job">The job.</param>
		/// <returns>
		/// True if job was executed successfully otherwise false if job failed
		/// </returns>
		public static Boolean RunJob(RunProcessElement job)
		{
			if (String.IsNullOrWhiteSpace(job.FileName)) { throw new ArgumentException("FileName is null or empty!"); }
			if (!File.Exists(job.FileName)) { throw new FileNotFoundException("The file '{0}' was not found", job.FileName); }

			try
			{
				var processStartInfo = new ProcessStartInfo
								{
									FileName = job.FileName,
									Arguments = job.Arguments,
									CreateNoWindow = true
								};
				var process = new Process() { StartInfo = processStartInfo, EnableRaisingEvents = true };
				process.ErrorDataReceived += (s, e) => Logging.WriteError("while executing Process '{0}': {1}", job.Name, e.Data);
				process.OutputDataReceived += (s, e) => Logging.WriteInformation("Process '{0}': {1}", job.Name, e.Data);
				process.Exited += (s, e) => { if (job.WaitSecondsToComplete <= 0) { Logging.WriteInformation("Process '{0}' has finished", job.Name); } };
				process.Start();

				while (!process.HasExited) { process.WaitForExit(10000); }

				// need to wati
				if (job.WaitSecondsToComplete > 0)
				{
					Logging.WriteInformation("Sleep timer found: wait for '{0}' seconds", job.WaitSecondsToComplete);
					Thread.Sleep(job.WaitSecondsToComplete * 1000);
					Logging.WriteInformation("Process '{0}' has finished", job.Name);
				}

				return true;
			}
			catch (Exception ex)
			{
				Logging.WriteError("while running process '{0}': {1}\n{2}", job.Name, ex.Message, ex.StackTrace);
				return false;
			}
		}

		#endregion Methods
	}
}